<template>
	<div class="system-user-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search mb15">
        <el-button size="default" type="success" class="ml10" @click="onOpenAdd">
          <el-icon>
            <ele-FolderAdd />
          </el-icon>
          新增中级证书
        </el-button>

			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="numb" label="中级证书编号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sign" label="根证书编号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="star" label="中级证书生效时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="stop" label="中级证书失效时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="unit" label="颁发组织" show-overflow-tooltip></el-table-column>
        <el-table-column prop="name" label="使用单元" show-overflow-tooltip></el-table-column>


				<el-table-column label="操作" width="200">
					<template #default="scope">
						<el-button  size="small" text type="primary" @click="downloadMiddleFn( scope.row)"
							><el-icon><ele-Bottom /></el-icon>下载</el-button
						>
            <el-button  size="small" text type="primary"  icon="el-icon-delete"  @click="onRowDel(scope.row)"
            ><el-icon><ele-Delete /></el-icon>删除</el-button
            >
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30]"
				v-model:current-page="state.tableData.param.pageNum"
				background
				v-model:page-size="state.tableData.param.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</el-card>
<!--		<UserDialog ref="userDialogRef" @refresh="getTableData()" />-->
    <RootDialog ref="rootDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="systemUser">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {getMiddleList,deleteMiddle,downloadMiddle} from '/@/api/cec/cert';

import  cityJson from  '/@/assets/json/city.json';
const rootDialogRef = ref();

// 引入组件
const RootDialog = defineAsyncComponent(() => import('/@/views/cert/middle/dialog.vue'));
// const UserDialog = defineAsyncComponent(() => import('/@/views/system/user/dialog.vue'));
// 打开新增菜单弹窗
const onOpenAdd = (type: string) => {
  rootDialogRef.value.openDialog(type);
};
// 定义变量内容

let now = new Date();
let yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
let month=yesterday.getMonth()+1;
let day=yesterday.getDate();

let monthStr="";
let dayStr="";
if(Number(month)<10){
  monthStr='0'+month;
}else{
  monthStr=month+'';
}
if(Number(day)<10){
  dayStr='0'+day;
}else{
  dayStr=day+'';
}

let  yesterdayDate = yesterday.getFullYear()+monthStr +dayStr;


const state = reactive({
  form: { size: 5, page: 1},
  rules: {
    time: { required: true, message: '请输入当前日期', trigger: 'blur' },
    size: { required: true, message: '请输入页面行数', trigger: 'blur' },
    page: { required: true, message: '请输入页面页数', trigger: 'blur' },
  },
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			pageNum: 1,
			pageSize: 10,
		},
	},
});

// 初始化表格数据
const getTableData =async () => {
	state.tableData.loading = true;


  state.form.size=state.tableData.param.pageSize;
  state.form.page=state.tableData.param.pageNum;

  const {code,msgs,data,tota}=await  getMiddleList(state.form);

  if(code===0){
    state.tableData.data = data;
    state.tableData.total = tota;
    setTimeout(() => {
      state.tableData.loading = false;
    }, 500);
  }else{
    ElMessage("请求错误！")
  }

};
// 打开新增用户弹窗
// const onOpenAddUser = (type: string) => {
// 	userDialogRef.value.openDialog(type);
// };
// // 打开修改用户弹窗
// const onOpenEditUser = (type: string, row: any) => {
// 	userDialogRef.value.openDialog(type, row);
// };
//下载根证书
const  downloadMiddleFn= (row:any)=>{

  downloadMiddle({"numb":row.numb}).then((blob:any)=>{
    // console.log(data)
    // const blob = new Blob([data])
    const fileName = 'Middle.crt'
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a')//创建一个a标签通过a标签的点击事件区下载文件
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)//使用blob创建一个指向类型数组的URL
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else if  (navigator.msSaveBlob){ // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  });



}
// 删除用户
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除根证书：“${row.numb}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
      const {code} = await deleteMiddle(row.numb);
      if (code == 0) {
        ElMessage.success('删除成功');
        getTableData();
      }

    })
		.catch(() => {});
};
const resetQuery=()=>{
  getTableData();
}
// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getTableData();
};
const formRulesThreeRef = ref();
//查询
// const searchList=async ()=>{
//   //校验
//   const valid = await formRulesThreeRef.value.validate().catch(() => {});
//   if (!valid) return false;
//   try {
//     getTableData();
//   } catch (error: any) {
//     // useMessage().error(error.msg);
//     ElMessage.warning(error.msg);
//   } finally {
//
//   }
//
//
// }
// 页面加载时
onMounted(() => {
	getTableData();
});
</script>

<style scoped lang="scss">
.system-user-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}
</style>
